<?php

namespace app\data\controller\api;

use app\data\service\CarService;
use think\admin\Controller;

/**
 * 汽车数据接口
 * Class Car
 * @package app\data\controller\api
 */
class Car extends Controller
{
    /**
     * 获取分车辆类型
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function vehicleType()
    {
        $carMonitoringStationId = $this->request->request('car_monitoring_station_id', 0);
        $this->success('获取车辆类型成功', CarService::instance()->vehicleTypes($carMonitoringStationId));
    }

    /**
     * 获取车辆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $query = $this->_query('CarInfos')->withoutField('deleted');
        $query->equal('id')->where(['uuid' => input('uuid'), 'deleted' => 0]);
        $result = $query->order('id desc')->page(true, false, false, input('limit', 15));
        foreach ($result['list'] as &$item) {
            if (is_null($item['register_date'])) {
                $item['register_date'] = '';
            } else {
                $item['register_date'] = date('Y-m-d', strtotime($item['register_date']));
            }
            if (is_null($item['issue_date'])) {
                $item['issue_date'] = '';
            } else {
                $item['issue_date'] = date('Y-m-d', strtotime($item['issue_date']));
            }
            if (empty($item['car_conditions'])) {
                $item['car_conditions'] = [];
            } else {
                $item['car_conditions'] = explode('、', $item['car_conditions']);
            }

            // todo 上一次年审的时间
            $item['last_inspection_record'] = '';
        }
        $this->success('获取汽车数据！', $result);
    }

    /**
     * 获取车辆详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $result = $this->app->db->name('CarInfos')->where('id', input('id'))->findOrEmpty();

        if (is_null($result['register_date'])) {
            $result['register_date'] = '';
        } else {
            $result['register_date'] = date('Y-m-d', strtotime($result['register_date']));
        }
        if (is_null($result['issue_date'])) {
            $result['issue_date'] = '';
        } else {
            $result['issue_date'] = date('Y-m-d', strtotime($result['issue_date']));
        }
        if (empty($result['car_conditions'])) {
            $result['car_conditions'] = [];
        } else {
            $result['car_conditions'] = explode('、', $result['car_conditions']);
        }

        $this->success('获取汽车数据！', $result);
    }
}